package com.fanpan26.aop.cglib;

import com.fanpan26.aop.jdk.Man;
import com.fanpan26.aop.jdk.WorkMan;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author fanpan26
 */
public class CGLigAgent implements MethodInterceptor {

    private Object proxy;

    public Object getInstance(Object proxy) {
        this.proxy = proxy;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.proxy.getClass());
        // 回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before");
        System.out.println(o instanceof WorkMan);
        methodProxy.invokeSuper(o,objects);
        System.out.println("after4");
        return null;
    }

    public static void main(String[] args) {
        CGLigAgent agent = new CGLigAgent();
        ((WorkMan)agent.getInstance(new WorkMan())).sayHello();
    }
}
